import os
import time

def write_db_file(db, config):
    db_str = '\n-'.join(['\n'.join(c) for c in db])
    f = open(os.path.join(config["PROFILE"], 'db'),'w')
    f.write(db_str)
    f.close()
    print db_str
    
def load_db_file(config):
    db_file = open(os.path.join(config['PROFILE'], 'db'))
    db = [[line for line in course.split('\n') if line.strip()] for course in db_file.read().split('-') if course.strip()]
    return db


config_file = open('config')
config = [tuple(line.split('=')) for line in config_file.read().split('\n') if line.strip()]
config_file.close()

if not config:
    config_file = open('config','w')
    config_file.write('PROFILE=default')
    config_file.close()
    config = {'PROFILE' : 'default'}
else:
    config = dict(config)

db = load_db_file(config)
current_course = ''
d = -1 # list to display
while(True):
    os.system('clear')
    if d == -1:
        print 'All courses:'
        for i, c in enumerate(db):
            print '['+str(i)+'] '+c[0]
    elif d == -2:
        d = -1
        print 'Movement: cd [#|.. or -1]'
        print 'Scanning: scan'
        print 'Make folder: mkcrs [folder name]'
        print 'Viewing item: view [#]'
        print 'Renaming: rename [#] [name]'
    else:
        print current_course+':'
        for i, img in enumerate(db[d][1:]):
            ltime = time.localtime(int(img.split('`')[1].split('.')[0]))
            stime = time.strftime("%a, %d %b %Y %H:%M:%S", ltime)
            print '['+str(i)+'] '+ img.split('`')[0]+' ('+stime+')'
    
    inp = raw_input('>')
    if inp == 'quit': quit()
    elif inp.strip() == 'help':
        d = -2
        current_course = ''
    elif inp.startswith('cd '):
        inp = inp[3:]
        if inp.isdigit() and int(inp) < len(db) and int(inp) >= 0:
            d = int(inp)
            current_course = db[d][0]
        elif inp == '-1' or inp == '..':
            d = -1
            current_course = ''
    elif inp == 'scan' and d > -1:
        comment = raw_input('Comment: ').replace('`', '') # lol security hole
        scanfile = str(int(time.time()))+'.tiff'
        imgstring = comment+'`'+scanfile
        print 'Scanning...'
        os.system('scanimage --format=TIFF --resolution 200 > '+os.path.join(config['PROFILE'], '\ '.join(current_course.split()), scanfile))
        db[d].append(imgstring)
        write_db_file(db, config)
    elif inp.startswith('mkcrs ') and inp[6:].strip():
        inp = inp[6:]
        db.append([inp])
        os.mkdir(os.path.join(config['PROFILE'], inp))
        write_db_file(db, config)
    elif inp.startswith('view ') and d > -1:
        inp = inp[5:]
        if inp.isdigit() and int(inp) < len(db[d][1:]):
            imgfile = db[d][1:][int(inp)].split('`')[1]
            imgpath = os.path.join(config["PROFILE"], '\ '.join(current_course.split()), imgfile) 
            os.system('gthumb --viewer ' + imgpath)
    elif inp.startswith('rename ') and inp[7:].strip():
        inp = [inp[7:].split()[0], ' '.join(inp[7:].split()[1:]).replace('`','')]
        if not inp[0].isdigit(): continue
        idex = int(inp[0])
        if d == -1 and idex < len(db):
            db[idex][0] = inp[1]
            write_db_file(db, config)
        else:
            db[d][idex+1] = inp[1]+'`'+db[d][idex+1].split('`')[1]
            write_db_file(db, config)
            db = load_db_file(config)
                
